package com.study.bindview;

import android.app.Activity;
import android.view.View;

import java.util.HashMap;
import java.util.Map;

/**
 * 作者： zjf 10/15/20 1:26 PM
 * 参考：
 * 描述：绑定activity类
 */
public class BindViewUtil {

    private final static Finder finder = new Finder() {
        @Override
        public View findView(Object source, int id) {
            if (source instanceof Activity) {
                return ((Activity) source).findViewById(id);
            } else if (source instanceof View) {
                return ((View) source).findViewById(id);
            } else {
                throw new RuntimeException("source没有提供findViewById(int id)方法");
            }
        }
    };

    //提供一个注入类的缓存,key为绑定的类的类名
    private final static Map<String, Injector<?>> injectorCache = new HashMap<>();

    /**
     * 绑定Activity使用
     */
    public static void bind(Activity target) {
        bind(target, target);
    }

    /**
     * 绑定Fragment或ViewHolder使用
     */
    public static void bind(Object target, Object source) {
        String targetClassName = target.getClass().getName();

        //从缓存获取注入类
        Injector injector = injectorCache.get(targetClassName);
        try {
            if (injector == null) {
                Class<?> clazz = Class.forName(targetClassName + "_Injector");
                injector = (Injector<?>) clazz.newInstance();
                injectorCache.put(targetClassName, injector);
            }

            //执行注入
            injector.inject(target, source, finder);
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }
}
